﻿/* 通过子节点，生成mesh对应的顶点
 * 
 */
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
[ExecuteInEditMode]
public class MeshByChildren : MonoBehaviour
{
    MeshFilter filter;
    //MeshRenderer renderer;
    public int VertexCount = 4;
    public string trianglesTips = "";
    public string exportPath = "\\Assets\\3rd\\FbxExporter";
    private void Awake()
    {
        
        //renderer = GetComponent<MeshRenderer>();

        


    }
    private void OnEnable()
    { 
        filter = GetComponent<MeshFilter>();
        GenVertex();
    }

    private void OnDestroy()
    {
        
    }
    private void OnDrawGizmos()
    {
        if (filter == null) return;
        var mesh = filter.sharedMesh;


        var trans = GetComponentInChildren<Transform>();
        List<Vector3> vertex = new List<Vector3>();
        foreach (Transform t in trans) {
            vertex.Add(t.localPosition);
        }
        mesh.SetVertices(vertex);
        //先暂时这样吧，到时候做个广度，深度测试
        //在之后做个判断外部，filter内部
        //int[] triangles = new int[] { 0, 1, 2, 0, 2, 3 };//只有1个面
  
        int[] triangles = new int[] { 0, 1, 2, 0, 1, 3, 1, 2, 3 };
        //每个三角面，反转并没有什么用
        //（和我们正常人理解的左右不同，计算机只会按照一定规则绘制，顺序和反序对计算机无差）
        //当然绘制先后次序有差，出来效果也会整体反转，
        // (整体倒转和每个三角面倒转无差）
        //所以，达不到左右互换效果
        //（左右取决于顶点位置 + 三角面）
        //triangles = revertTriangles(triangles);

        //三角顺序 顺时针 才会是你想看的面的绘制 逆时针就是反面了
        //triangles = revert(triangles);
        trianglesTips = string.Join(",", Array.ConvertAll(triangles, Convert.ToString));
        mesh.SetTriangles(triangles, 0);
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
        //this.GetComponent<MeshCollider>().sharedMesh = mesh;

        //UV贴图的四个点，和顶点一一对应，左下角为(0,0)，右上角为(1,1)
        //如果顶点顺序没有跟UV对应，贴图就会出现问题
        Vector2[] uvs = new Vector2[]
        {
            new Vector2(0, 0),//第一个点
            new Vector2(0,1), //2
            new Vector2(1,1),//3
            new Vector2(1,0),
        };
        mesh.uv = uvs;
    }
    [ContextMenu("生成顶点（子节点）")]
    void GenVertex() {
        //顺时针分布
        int childCount = transform.childCount;
        for (int i=childCount; i < VertexCount - childCount; i++)
        {

            var go = new GameObject("Ver" + i);
            go.transform.parent = transform;
        }
    }
    [ContextMenu("导出Fbx")]
    void ExportFbx() {
#if UNITY_EDITOR
        if (filter == null || filter.sharedMesh == null)
        {
            return;
        }
        //因为会自动创造目录，所以录入目录要注意。。。。。

        //if(exportPath.StartsWith("\\")==false)
        //    exportPath = "\\" + exportPath;
        if (exportPath.StartsWith("\\Assets\\") == true || exportPath.StartsWith("/Assets/") == true)
        {
            exportPath = exportPath.Substring(8);//不需要需要前面的 "\" 或 "/",例如： 3rd\xxxxx
            //因为后面  FBXExporter.ExportFBX 多了一个 "/"会出错
        }
        if (exportPath.StartsWith("\\") || exportPath.StartsWith("/"))
        {
            exportPath = exportPath.Substring(1);
        }
        string path = Application.dataPath + "/" + exportPath;
        string folderPath = Path.GetDirectoryName(path);
        //TODO:jia检测是否存在重名文件
        if (Directory.Exists(folderPath) ==false){
            Directory.CreateDirectory(folderPath);
        }
        string fbxname = Path.GetFileNameWithoutExtension(path);

        //string exportFolder = Path.GetDirectoryName(exportPath);
        string exportFolder = exportPath;
        string[] exportsplit = exportFolder.Split('/');
        if (exportsplit.Length > 0) {
            exportFolder = "";
            for (int i = 0; i < exportsplit.Length-1; i++)
            {
                exportFolder = exportFolder + "/" + exportsplit[i];
            }
        }
        GameObject[] meshObjs = new GameObject[] { gameObject };
        FBXExporter.ExportFBX(exportFolder, fbxname, meshObjs, true);
#endif
    }
    public int[] revertTriangles(int[] src) {  

        List<int> destList = new List<int>();
        for (int i = 0; i < src.Length / 3; i++)
        {
            int[] subLine = new int[] { src[i * 3], src[i * 3 + 1], src[i * 3 + 2] };
            subLine = revert(subLine);
            destList.AddRange(subLine);
        }
        return destList.ToArray();
    }
    public int[] revert(int[] src) {
        int[] dest = new int[src.Length];
        for (int i = src.Length - 1; i >= 0; i--)
        {
            dest[src.Length - i -1] = src[i];
        }
        return dest;

    }

}
    

